﻿<script setup lang="ts" name="DebounceThrottle">
import * as _ from 'lodash'
import { storeToRefs } from 'pinia'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'
import { successMessage } from '@/utils/message'

const systemConfigStore = useSystemConfigStore()
const { systemConfig } = storeToRefs(systemConfigStore)
const clickHandle = () => {
  successMessage('成功执行了点击事件')
}
const debounceClick = _.debounce(clickHandle, 1000, { leading: true, trailing: false })
const debouncedClick = _.debounce(clickHandle, 1000, { leading: false, trailing: true })
const throttleClick = _.throttle(clickHandle, 1000)
</script>

<template>
  <el-space :size="systemConfig.space" fill alignment="stretch" style="flex-wrap: nowrap">
    <el-row :gutter="systemConfig.space">
      <el-col :xs="24" :sm="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>防抖 Debounce</span>
            </div>
          </template>
          <el-alert title="对于短时间内连续触发事件（滚动事件、表单重复提交、页面resize事件），让某个时间期限内，事件处理函数只执行一次" type="success" :closable="false" show-icon />
          <el-button @click="debounceClick">连续点击我，只会执行第一次点击事件，立即执行</el-button>
          <el-button @click="debouncedClick">连续点击我，只会执行最后一次点击事件，延迟执行</el-button>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>节流 Throttle</span>
            </div>
          </template>
          <el-alert title="对于短时间内大量触发同一事件（滚动事件、输入框实时搜索事件），在函数执行一次后，该函数在指定的时间期限内不再次执行，直到过了这段时间期限才重新生效可再次执行" type="success" :closable="false" show-icon />
          <el-button @click="throttleClick">连续点击我，设定每一秒只会执行一次点击事件</el-button>
        </el-card>
      </el-col>
    </el-row>
  </el-space>
</template>

<style scoped lang="scss">
.el-space {
  width: 100%;
  padding: var(--el-space) var(--el-space) 0;
}

.el-row {
  flex: 1;

  .el-col {
    display: flex;

    .el-card {
      flex: 1;
    }
  }
}

.el-alert {
  margin-bottom: 20px;
}
</style>
